package com.cloudeasy.post.controller;

import com.cloudeasy.api.util.ResultUtil;
import com.cloudeasy.api.vo.Result;
import com.cloudeasy.api.vo.post.VoteVO;
import com.cloudeasy.core.bean.JwtParser;
import com.cloudeasy.post.service.VoteService;
import com.cloudeasy.post.util.VoteUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@CrossOrigin
@RequestMapping("/vote")
public class VoteController {
    private final VoteService voteService;

    private final JwtParser jwtParser;

    @Autowired
    public VoteController(VoteService voteService, JwtParser jwtParser) {
        this.voteService = voteService;
        this.jwtParser = jwtParser;
    }

    /**
     * 点赞评论
     *
     * @param authentication {@link Authentication}
     * @param replyId        评论Id
     * @param type           类型
     * @return {@link Result<Boolean>}
     */
    @PostMapping("/{replyId}/{type}")
    public Result<Boolean> like(Authentication authentication,
                                @PathVariable("replyId") String replyId,
                                @PathVariable("type") Integer type) {
        String userId = (String) jwtParser.getOnBody(authentication, "userId");
        return ResultUtil.success(voteService.like(userId, replyId, type));
    }

    /**
     * 移除点赞评论
     *
     * @param authentication {@link Authentication}
     * @param replyId        评论Id
     * @return {@link Result<Boolean>}
     */
    @DeleteMapping("/{replyId}")
    public Result<Boolean> removeLike(Authentication authentication,
                                @PathVariable("replyId") String replyId) {
        String userId = (String) jwtParser.getOnBody(authentication, "userId");
        return ResultUtil.success(voteService.removeLike(userId, replyId));
    }

    /**
     * 获取当前用户的点赞
     *
     * @param authentication {@link Authentication}
     * @return {@link List<VoteVO>}的{@link Result}
     */
    @GetMapping
    public Result<List<VoteVO>> currentLike(Authentication authentication) {
        String userId = (String) jwtParser.getOnBody(authentication, "userId");
        return ResultUtil.success(VoteUtil.convert(voteService.getLikeByUserId(userId)));
    }
}
